import { searchCover, isString, isNumber, toObject, round } from "@/common.js"
// 处理表单数据为对象键值对形式
export const getTemplateData = function (formTemplate) {
  const formTemplateData = formTemplate.map(v => {
    const newItem = Object.keys(v).reduce((prev, item) => {
      if(item.includes('key')) { prev[v[item]] = v[item.replace('key', 'value')] }
      return prev
    }, {})
    return newItem 
  })
  return toObject(formTemplateData)
}
// 处理用户的输入
export const handleInput = function (e) {
  let value = isString(e) || isNumber(e) ? e : e.target.value
  const _value = value
  if(this.item.decimal) {
    value = String(value).replace(/[^0-9.]/g, '') // 非数字、点、负号，替换为空
    const res = value.match(/([^.]*)([.])?([^.]*)/)
    const [origin, left = '', dot = '', right = ''] = res
    value = `${left}${dot}${right.slice(0, Number(this.item.decimal))}`
  }
  if(value != _value) {
    this.$Message.info(`只能输入数字，保留${this.item.decimal}位小数`)
  }
  let errmsg = value.length > this.item.maxlength ? `文本最大长度为${this.item.maxlength}` : ''
  // 正则校验
  // const reg = eval(`new RegExp(${this.item.regExp})`)
  // const flag = reg.test(value)
  // 更新当前条目值
  value = value.slice(0, this.item.maxlength)
  const item = {...this.item, value, errmsg}
  this.$emit('setItem', item)
  // console.log(this.formData)
  // 更新整体表单的值
  let formData = searchCover(this.formData, {id: this.item.id}, v => ({...v, value, errmsg}))
  formData = formData.map(v => ({...v, children: v.type == 'split' ? searchCover(v.children, {id: this.item.id}, v => ({...v, value, errmsg})) : v.children}))
  this.$emit('setFormData', formData)
  eval(this.item.onChange)(e)
}
// 监听聚焦
export const handleFocus = function (e) {
  eval(this.item.onFocus)(e)
}
// 监听失去焦点
export const handleBlur = function (e) {
  eval(this.item.onBlur)(e)
}